#include <stdio.h>
#include <string.h>
#include <math.h>
#include "ftoa.h"
#include "lpc_types.h"
const double eps = 1e-12;

char s[30];

void reverse_ftoa(char *s)
{
     int i , j;
     int len = strlen(s);
     for( i = 0 , j = len - 1 ; i < j ; i++ , j--)
         s[i]^=s[j]^=s[i]^=s[j];
}
 
 /* ftoa:   convert double n to string s with digits*/
void ftoa(char *s, double n, int digits)
{
     
	 int i = 0 , p, cur_d;
	 long long t;
	 Bool sign = 1;
	 memset(s , 0 , sizeof(s));
     
     
     if( n < 0 ) 
     { 
         sign = 0;
         n = -n;
     }
      t = (long long)n;
     n = n - t;
     if( t == 0)
     {
         s[i++] = '0';
     }
     else
     {
         while( t != 0 )
         {
             p = t % 10;
             t /= 10;
             s[i++] = p + '0';
         }
         if(!sign) s[i++] = '-';
         reverse_ftoa(s);
     }
     if( fabs( n - 0.0 ) > eps )
     {
         s[i++] = '.';
         cur_d = 0;
         while( cur_d < digits)
         {
             cur_d++;
             n *= 10.0;
             p = ( long)n;
             n = n - p;
             s[i++] = p + '0';
         }
     }
     s[i] = '\0';
}